package com.example.star.json;

import android.content.Context;
import android.content.res.AssetManager;

import com.example.star.entity.Star;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.List;

public class JsonParser {
    public static List<Star> parseStarsFromJson(Context context, String jsonFileName) {
        AssetManager assetManager = context.getAssets();
        try {
            InputStream inputStream = assetManager.open(jsonFileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder jsonText = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonText.append(line);
            }
            reader.close();
            inputStream.close();

            Gson gson = new Gson();
            Type listType = new TypeToken<List<Star>>() {}.getType();
            return gson.fromJson(jsonText.toString(), listType);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
